package com.gitee.cui.netty.protocol;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Json解析服务端，接收客户端ByteBuf数据，解码成Json字符串数据，并将Json字符串数据转换成JsonMsgPOJO数据
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/25 13:13
 **/
public class JsonServer {

    private int serverPort;

    private ServerBootstrap bootstrap = new ServerBootstrap();

    public JsonServer(int serverPort) {
        this.serverPort = serverPort;
    }

    public static void main(String[] args) {
        new JsonServer(NettyDemoConfig.SOCKET_SERVER_PORT).runServer();
    }

    /**
     * 启动Netty服务器程序
     */
    private void runServer() {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new JsonMsgDecoder());
                }
            });
            bootstrap.localAddress(serverPort);

            ChannelFuture future = bootstrap.bind();
            future.sync();
            Logger.info(" 服务器启动成功，监听端口: " +
                    future.channel().localAddress());
            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    private class JsonMsgDecoder extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String json = (String) msg;
            JsonMsg jsonMsg = JsonMsg.parseFromJson(json);
            Logger.info("收到一个Json数据包=> " + jsonMsg);
        }
    }
}
